#!/usr/bin/env python3
# DESCRIPTION: Verilator: Verilog Test driver/expect definition
#
# Copyright 2024 by Wilson Snyder. This program is free software; you
# can redistribute it and/or modify it under the terms of either the GNU
# Lesser General Public License Version 3 or the Perl Artistic License
# Version 2.0.
# SPDX-License-Identifier: LGPL-3.0-only OR Artistic-2.0

import vltest_bootstrap

test.scenarios('vlt')
test.top_filename = test.obj_dir + "/t_vthread.v"


def gen(filename, n):
    with open(filename, 'w', encoding="utf8") as fh:
        fh.write("// Generated by t_vthread.py\n")
        fh.write("module genmod #(int val = 0)(clk, o);\n")
        fh.write("  input clk;\n")
        fh.write("  output int o;\n")
        fh.write("  always @ (posedge clk) begin\n")
        fh.write("    o <= val;\n")
        fh.write("  end\n")
        fh.write("endmodule\n")
        fh.write("module t (clk, o);\n")
        fh.write("  input clk;\n")
        fh.write("  output int o;\n")
        for i in range(0, n + 1):
            fh.write("  int r" + str(i) + ";\n")
            fh.write("  genmod #(.val(" + str(i) + ")) rm" + str(i) + " (.clk, .o(r" + str(i) +
                     "));\n")
        fh.write("  always @ (posedge clk) begin\n")
        fh.write("    o <= r" + str(n) + ";\n")
        fh.write('    $write("*-* All Finished *-*\\n");' + "\n")
        fh.write('    $finish;' + "\n")
        fh.write("  end\n")
        fh.write("endmodule\n")


gen(test.top_filename, 6000)

test.compile(
    # use --trace-vcd to generate trace files that can be parallelized
    verilator_flags2=["--stats --trace-vcd --verilate-jobs 2"])

test.execute()

test.file_grep(test.stats, r'Verilate jobs: 2')

test.passes()
